#pragma once
#include "Socket.hpp"
#include "Epoller.hpp"
#include "Log.hpp"
#include <string>
#include <iostream>
#include <memory>

using namespace NetWorkModule;
using namespace EpollModule;

const static int gbacklog = 32;

class EpollServer
{
    const static int maxevents = 64;

public:
    EpollServer(int port)
        : _port(port), _listensock(new TcpSocket()), _epoller(new Epoller()), _isrunning(false)
    {
    }
    bool InitServer()
    {
        // 1. 创建listensock
        _listensock->BuildListenSocketMethod((uint16_t)_port, gbacklog);
        lg.LogMessage(Info, "init socket success, listensock is %d\n", _listensock->GetSocket());
        // 2. 创建epoll模型
        _epoller->InitEpoller();
        lg.LogMessage(Info, "init epoller success\n");
        // 3. 将listensock添加到epoll中
        _epoller->AddEvent(_listensock->GetSocket(), EPOLLIN);
        return true;
    }
    int Recver(int sockfd, std::string *out)
    {
        char buffer[1024];
        int n = ::recv(sockfd, buffer, sizeof(buffer), 0);
        if(n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }
    std::string EventToString(uint32_t events)
    {
        std::string info;
        if(events & EPOLLIN) info += "EPOLLIN";
        if(events & EPOLLOUT) info += "EPOLLOUT";
        if(events & EPOLLET) info += "EPOLLET";

        return info;
    }
    bool Accepter(std::string *peerip, uint16_t *peerport)
    {
        // 监听事件就绪
        int sockfd = _listensock->AcceptConnection(peerip, peerport);
        if (sockfd < 0)
        {
            lg.LogMessage(Warning, "accept error\n");
            return false;
        }
        // 获取链接成功
        _epoller->AddEvent(sockfd, EPOLLIN);
        return true;
    }
    void HandlerEvent(int n)
    {
        lg.LogMessage(Debug, "%d 个 events 已经就绪\n", n);
        for (int i = 0; i < n; i++)
        {
            lg.LogMessage(Debug, "ready fd: %d, Event is: %s\n", _revs[i].data.fd, EventToString(_revs[i].events).c_str());
            int sockfd = _revs[i].data.fd;
            uint32_t events = _revs[i].events;
            if (events & EPOLLIN)
            {
                // 1. listen 2. normal sockfd
                if (sockfd == _listensock->GetSocket())
                {
                    std::string clientip;
                    uint16_t clientport;
                    if (!Accepter(&clientip, &clientport))
                    {
                        continue;
                    }
                    lg.LogMessage(Info, "accept client success, client[%s:%d]\n",
                                  clientip.c_str(), clientport);
                }
                else
                {
                    std::string message;
                    int n = Recver(sockfd, &message);
                    if(n > 0)
                    {
                        std::cout << "client# " << message << std::endl;
                        // 直接写
                        message.resize(message.size() - strlen("\r\n"));
                        std::string echo_message = "echo_message" + message + "\r\n";
                        send(sockfd, echo_message.c_str(), echo_message.size(), 0);
                    }
                    else
                    {
                        if(n == 0)
                        {
                            lg.LogMessage(Info, "client %d close\n", sockfd);
                        }
                        else
                        {
                            lg.LogMessage(Info, "client %d recv error\n", sockfd);
                        }
                        // epoll移除的fd必须是合法的才能正确移除
                        _epoller->DelEvent(sockfd);
                        ::close(sockfd);
                    }
                }
            }
        }
    }

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            _epoller->DebugFdList();
            int timeout = 1000;
            int n = _epoller->Wait(_revs, maxevents, timeout);
            switch (n)
            {
            case 0:
                lg.LogMessage(Debug, "timeout...\n");
                break;
            case -1:
                lg.LogMessage(Error, "epoll wait failed!\n");
                break;
            default:
                // 事件就绪
                lg.LogMessage(Info, "event happen ... \n");
                HandlerEvent(n);
                break;
            }
        }
        _isrunning = false;
    }
    ~EpollServer()
    {
    }

private:
    std::unique_ptr<Socket> _listensock;
    std::unique_ptr<Epoller> _epoller;
    int _port;
    bool _isrunning;
    struct epoll_event _revs[maxevents];
};